﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Logistics
{
    public class FtpHelper
    {
        public static FtpHelper Instance { get; }

        static FtpHelper()
        {
            Instance = new FtpHelper();
        }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string FtpPath { get; set; }

        /// <summary>  
        /// 取得文件名  
        /// </summary>  
        public string[] GetFilePath()
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpPath));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(UserName, Password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                reqFTP.UsePassive = false;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                downloadFiles = null;
                return downloadFiles;
            }
        }

        //ftp的上传功能  
        public void Upload(string category, string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            FtpWebRequest reqFTP;
            // 根据uri创建FtpWebRequest对象   
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpPath + category + fileInf.Name));
            // ftp用户名和密码  
            reqFTP.Credentials = new NetworkCredential(UserName, Password);

            reqFTP.UsePassive = false;
            // 默认为true，连接不会被关闭  
            // 在一个命令之后被执行  
            reqFTP.KeepAlive = false;
            // 指定执行什么命令  
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // 指定数据传输类型  
            reqFTP.UseBinary = true;
            // 上传文件时通知服务器文件的大小  
            reqFTP.ContentLength = fileInf.Length;
            // 缓冲大小设置为2kb  
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件  
            FileStream fs = fileInf.OpenRead();
            try
            {
                // 把上传的文件写入流  
                Stream strm = reqFTP.GetRequestStream();
                // 每次读文件流的2kb  
                contentLen = fs.Read(buff, 0, buffLength);
                // 流内容没有结束  
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream  
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                // 关闭两个流  
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Delete(string category, string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpPath + category + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(UserName, Password);
                reqFTP.UsePassive = false;
                FtpWebResponse listResponse = (FtpWebResponse)reqFTP.GetResponse();
                string sStatus = listResponse.StatusDescription;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //从ftp服务器上下载文件的功能  
        public void Download(string filePath, string category, string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpPath + category + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(UserName, Password);
                reqFTP.UsePassive = false;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 检测目录是否存在
        /// </summary>
        public bool CheckDirectory(List<string> categorys, string ftpPath, string category = null)
        {
            var subCategory = category;
            if (subCategory == null)
                subCategory = categorys.FirstOrDefault();
            if (ftpPath == null)
                ftpPath = FtpPath;
            //检测目录是否存在
            Uri uri = new Uri(ftpPath + subCategory + "/");
            if (!DirectoryIsExist(uri))
            {
                if (CreateDirectory(uri))
                {

                }
            }
            categorys.Remove(subCategory);
            subCategory = categorys.FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(subCategory))
                CheckDirectory(categorys, uri.ToString(), subCategory);
            return true;
        }
        /// <summary>
        /// ftp创建目录(创建文件夹)
        /// </summary>
        /// <returns></returns>
        public bool CreateDirectory(Uri ftpPath)
        {
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpPath);
                reqFTP.Credentials = new NetworkCredential(UserName, Password);
                reqFTP.Proxy = null;
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                FtpWebResponse response = reqFTP.GetResponse() as FtpWebResponse;
                response.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 检测目录是否存在
        /// </summary>
        public bool DirectoryIsExist(Uri ftpPath)
        {
            string[] value = GetFileList(ftpPath);
            if (value == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public string[] GetFileList(Uri ftpPath)
        {
            StringBuilder result = new StringBuilder();
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpPath);
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(UserName, Password);
                // reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                //  return new string[0];
                return null;
            }
        }
    }
       
}
